<?php
use Hoa\Registry\Registry;
use Illuminate\Container\Container as LContainer;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Events\Dispatcher as LDispatcher;
// use Library\Log;
use Philo\Blade\Blade;
use Dotenv\Dotenv;


/**
 * Bootstrap
 * 这里所有的公共方法，都会被执行，执行的次序, 和申明的次序相同
 */
class Bootstrap {
	/**
	 * 加载环境配置文件
	 */
	static public function _initEnv() {
		$dotenv = new Dotenv(PRJ_PATH);
		$dotenv->load();
	}


	/**
	 * 注册配置信息
	 */
	static public function _initCnf() {
		$conf = require PRJ_PATH . 'conf/conf.php';
		Registry::set('conf', $conf);
	}


	/**
	 * 注册函数和自动加载类
	 */
	static public function _initLoad() {
		//注册函数
		require APP_PATH . 'function/function.php';

		//自动加载类
		spl_autoload_register('load_class');
	}


	/**
	 * 初始化Eloquent ORM
	 */
	static public function _initDefaultDbAdapter() {
		$conf = Registry::get('conf');
		$capsule = new Capsule();
		$capsule->addConnection($conf['database']['default'], 'default');
		//$capsule->addConnection($conf['database']['mydb'], 'mydb');
		$capsule->setEventDispatcher(new LDispatcher(new LContainer));
		$capsule->setAsGlobal();
		$capsule->bootEloquent();
	}


	/**
	 * 注册Blade模板引擎
	 */
	static public function _initBlade(){
		//default module
		$viewPaths = APP_PATH . 'views';
		$cachePath = PRJ_PATH . 'runtime/cache';
		if (!is_dir($cachePath)) {
			mkdir($cachePath, 0755, true);
		}
		$blade = new Blade($viewPaths, $cachePath);
		Registry::set('blade', $blade);
	}


}


/**
 * 自动加载类，类的目录为/app/Controller, /app/Library, /app/Logic, /app/Model, /app/Service
 * @param string $class
 */
function load_class($class) {
	//Log::debug('load_class: ' . $class);
	$path = str_replace('\\', '/', $class);
	$realpath = APP_PATH . $path . '.php';
	if (is_file($realpath)) {
		//Log::debug('realpath: ' . $realpath);
		require_once $realpath;
	}
}


/**
 * 执行Bootstrap类的static public方法
 */
$bootstrapMethodList = get_class_methods('Bootstrap');
foreach ($bootstrapMethodList as $method) {
	Bootstrap::$method();
}

